package com.axx.android.letter.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.axx.android.LetterApp;
import com.axx.android.R;
import com.axx.android.base.BaseActivity;
import com.axx.android.common.BaseModel;
import com.axx.android.common.Constants;
import com.axx.android.home.model.User;
import com.axx.android.letter.model.LetterDetail;
import com.axx.android.letter.model.ResetPathResult;
import com.axx.android.profile.auth.activity.LoginActivity;
import com.axx.android.utils.DateUtils;
import com.axx.android.utils.GsonUtils;
import com.axx.android.utils.HttpUtils;
import com.axx.android.utils.ImageLoader;
import com.axx.android.utils.ImageUtils;
import com.axx.android.utils.MapUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.previewlibrary.PhotoActivity;
import com.previewlibrary.ThumbViewInfo;
import com.sendtion.xrichtext.DataImageView;
import com.sendtion.xrichtext.RichTextView;
import com.sendtion.xrichtext.StringUtils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LetterDetailActivity extends BaseActivity {

    @Bind(R.id.btn_back)
    Button btnBack;
    @Bind(R.id.tv_location)
    TextView tvLocation;
    @Bind(R.id.tv_status)
    TextView tvStatus;
    @Bind(R.id.iv_from)
    ImageView ivFrom;
    @Bind(R.id.tv_from)
    TextView tvFrom;
    @Bind(R.id.tv_no)
    TextView tvNo;
    @Bind(R.id.iv_to)
    ImageView ivTo;
    @Bind(R.id.tv_to)
    TextView tvTo;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_content)
    RichTextView tvContent;
    @Bind(R.id.tv_start_time)
    TextView tvStartTime;
    @Bind(R.id.tv_distance)
    TextView tvDistance;
    @Bind(R.id.layout_option)
    LinearLayout layoutOption;
    @Bind(R.id.btn_location)
    Button btnLocation;
    @Bind(R.id.tv_end_time)
    TextView tvEndTime;
    @Bind(R.id.btn_replay)
    Button btnReplay;
    @Bind(R.id.layout_end_time)
    LinearLayout layoutEndTime;
    @Bind(R.id.tv_surplus)
    TextView tvSurplus;
    @Bind(R.id.layout_surplus)
    LinearLayout layoutSurplus;
    @Bind(R.id.tv_energy)
    TextView tvEnergy;
    @Bind(R.id.iv_up)
    ImageView mIvUp;
    @Bind(R.id.iv_like)
    ImageView mIvLike;
    @Bind(R.id.tv_up_cnt)
    TextView mTvUpCnt;
    @Bind(R.id.btn_del)
    Button btnDel;
    @Bind(R.id.btn_share)
    Button btnShare;
    @Bind(R.id.rb_start)
    RatingBar rbStart;

    private String from;
    private LetterDetail model;
    private String role;
    private String id;

    @Override
    public int getLayoutId() {
        return R.layout.activity_letter_detail;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        from = getIntent().getStringExtra("from");
        id = getIntent().getStringExtra("id");

        showLoading("");
        fetchLetter();
    }

    private void fetchLetter() {
        HashMap<String, String> map = new HashMap();
        map.put("id", id);
        if (LetterApp.authUser != null) {
            map.put("userId", LetterApp.authUser.getId());
        }
        HttpUtils.post(Constants.Url.Letter.LETTER_GET, map, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                BaseModel<LetterDetail> detailBaseModel = null;
                try {
                    detailBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<LetterDetail>>() {
                    });
                    if (detailBaseModel.isSuccess()) {
                        model = detailBaseModel.data;
                        renderUI();
                    } else {
                        showToast(detailBaseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                hideLoading();
                showErrorNet();
            }
        });
    }

    private void renderUI() {
        renderUserHeader();
        renderLocation();
        renderDisplay();
        rbStart.setRating((float) model.getMood());
    }

    private void renderDisplay() {
        if (LetterApp.authUser == null) {
            renderViewer();
        } else {
            if (LetterApp.authUser.getId().equals(model.getFromUser().getId())) {
                renderSender();
                role = "sender";
            } else if (LetterApp.authUser.getId().equals(model.getToUser().getId())) {
                renderReceiver();
                role = "receiver";
            } else {
                renderViewer();
            }
        }
//        if ("home".equals(from)) {
//            renderViewer();
//        }
//        if ("detail".equals(from)) {
//            if (LetterApp.authUser.getId().equals(model.getFromUser().getId())) {
//                renderSender();
//                role = "sender";
//            } else {
//                renderReceiver();
//                role = "receiver";
//            }
//        }
    }

    private void renderReceiver() {
        btnDel.setVisibility(View.VISIBLE);
        if ("1".equals(model.getStatus())) {
            //已到达
            layoutOption.setVisibility(View.VISIBLE);
            layoutEndTime.setVisibility(View.VISIBLE);
            tvEndTime.setText(model.getArriveTime());
            btnReplay.setVisibility(View.VISIBLE);
            mTvUpCnt.setText(model.getGood() + "");
            if (model.getGoodStatus() == 1) {
                mIvUp.setSelected(true);
            }
            if (model.getCollectionStatus() == 1) {
                mIvLike.setSelected(true);
            }
            renderLetterBody();
        } else {
            //未到达
            btnLocation.setVisibility(View.VISIBLE);
            tvTitle.setText("通知：" + model.getFromUser().getNickName() + "的信正在路上，请稍后");
            tvSurplus.setText(DateUtils.getDiffTime(model.getArriveTime()));
            layoutSurplus.setVisibility(View.VISIBLE);
        }
    }

    private void renderSender() {
        btnDel.setVisibility(View.VISIBLE);
        renderLetterBody();
        if ("1".equals(model.getStatus())) {
            //已到达
            layoutEndTime.setVisibility(View.VISIBLE);
            tvEndTime.setText(model.getArriveTime());
        } else {
            //未到达
            layoutSurplus.setVisibility(View.VISIBLE);
            tvSurplus.setText(DateUtils.getDiffTime(model.getArriveTime()));
            btnLocation.setVisibility(View.VISIBLE);
        }
    }


    private void renderViewer() {
        layoutOption.setVisibility(View.VISIBLE);
        layoutSurplus.setVisibility(View.VISIBLE);

        mTvUpCnt.setText(model.getGood() + "");


        if ("1".equals(model.getStatus())) {
            //已到达
            layoutSurplus.setVisibility(View.GONE);
            layoutEndTime.setVisibility(View.VISIBLE);
            tvEndTime.setText(model.getArriveTime());
        } else {
            //未到达
            tvSurplus.setText(DateUtils.getDiffTime(model.getArriveTime()));
        }

        if (LetterApp.authUser != null && LetterApp.authUser.getId().equals(model.getToUser().getId())) {
            tvTitle.setText("通知：" + model.getFromUser().getNickName() + "的信正在路上，请稍后");
        } else {
            renderLetterBody();
        }

        if (model.getGoodStatus() == 1) {
            mIvUp.setSelected(true);
        }
        if (model.getCollectionStatus() == 1) {
            mIvLike.setSelected(true);
        }
    }

    private void renderLocation() {
        tvLocation.setText(model.getFromPlace() + "至" + model.getToPlace());
        tvStatus.setText(model.getStatus().equals("0") ? "正在路上" : "已到达");
    }

    private void renderLetterBody() {
        tvTitle.setText(model.getTitle());
        showEditData(model.getText());
    }

    final ArrayList<ThumbViewInfo> thumbViewInfos = new ArrayList<>();

    private void showEditData(String html) {
        tvContent.setImageClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DataImageView imageView = (DataImageView) view;
                String image = imageView.getAbsolutePath();
                int postion = 0;
                for (int i = 0; i < thumbViewInfos.size(); i++) {
                    if (image.equals(thumbViewInfos.get(i).getUrl())) {
                        postion = i;
                    }
                }
                PhotoActivity.startActivity(LetterDetailActivity.this, thumbViewInfos, postion);

            }
        });

        List<String> textList = StringUtils.cutStringByImgTag(html);
        for (String text : textList) {
            if (text.contains("<img") && text.contains("src=")) {
                String imagePath = StringUtils.getImgSrc(text);
                if (imagePath.contains("http://axx.oss-cn-shenzhen.aliyuncs.com")) {
                    tvContent.addImageViewAtIndex(tvContent.getLastIndex(), imagePath);

                    ThumbViewInfo thumbViewInfo = new ThumbViewInfo(imagePath);
                    thumbViewInfos.add(thumbViewInfo);
                }
            } else {
                tvContent.addTextViewAtIndex(tvContent.getLastIndex(), text);
            }
        }
    }

    private void renderUserHeader() {
        if (model != null) {
            if (model.getFromUser() != null) {
                ImageLoader.loadRoundImage(model.getFromUser().getHeadPic(), ivFrom, this);
                tvFrom.setText(model.getFromUser().getNickName());
            }
            if (model.getToUser() != null) {
                ImageLoader.loadRoundImage(model.getToUser().getHeadPic(), ivTo, this);
                tvTo.setText(model.getToUser().getNickName());

            }
        }
        tvDistance.setText(model.getDistance() + "km");
        tvStartTime.setText(model.getSendTime());
        tvEnergy.setText(model.getEnergy() + "张");
        tvNo.setText("To " + model.getTrains() + "次");

        ivFrom.setTag("from");
        ivTo.setTag("to");
        ivTo.setOnClickListener(headerClick);
        ivFrom.setOnClickListener(headerClick);

    }

    private View.OnClickListener headerClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String userString;
            LatLng from;
            LatLng to;
            if (view.getTag().toString().equals("to")) {
                userString = GsonUtils.toJson(model.getToUser());
                from = new LatLng(LetterApp.curLocation.getLatitude(), LetterApp.curLocation.getLongitude());
                to = new LatLng(model.getFromUser().getLatitude(), model.getToUser().getLongitude());

            } else {
                userString = GsonUtils.toJson(model.getFromUser());
                from = new LatLng(LetterApp.curLocation.getLatitude(), LetterApp.curLocation.getLongitude());
                to = new LatLng(model.getFromUser().getLatitude(), model.getFromUser().getLongitude());
            }
            try {
                User.UserListBean userListBean1 = GsonUtils.fromJson(userString, new TypeToken<User.UserListBean>() {
                });

                float distance = AMapUtils.calculateLineDistance(from, to);
                String stringTime = String.format(Locale.US, "%.2f", distance / 1000);
                userListBean1.setDistance(Double.parseDouble(stringTime));

                Intent intent = new Intent(LetterDetailActivity.this, RecipientActivity.class);
                intent.putExtra("model", userListBean1);
                startActivity(intent);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };


    @OnClick(R.id.btn_location)
    public void onViewClicked() {
        showLoading("");
        fetchResetCarPath();
    }

    private void fetchResetCarPath() {
        HashMap<String, String> map = new HashMap<>();
        map.put("nowLongitude", model.getNowLongitude() + "");
        map.put("nowLatitude", model.getNowLatitude() + "");
        map.put("letterId", model.getId());
        map.put("toPlace", MapUtils.getCity(LetterApp.curLocation.getAdCode()));
        map.put("toLongitude", LetterApp.curLocation.getLongitude() + "");
        map.put("toLatitude", LetterApp.curLocation.getLatitude() + "");
        map.put("type", "sender".equals(role) ? "1" : "0");
        HttpUtils.post(Constants.Url.Letter.LETTER_RESET_PATH, map, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    hideLoading();
                    BaseModel<ResetPathResult> baseModel;
                    baseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<ResetPathResult>>() {
                    });
                    if (baseModel.isSuccess()) {
                        Intent intent = new Intent(LetterDetailActivity.this, LetterMapActivity.class);
                        intent.putExtra("role", role);
                        intent.putExtra("model", baseModel.data);
                        intent.putExtra("detail", model);
                        startActivity(intent);
                    } else {
                        showToast(baseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError() {
                hideLoading();
                showErrorNet();
            }
        });
    }

    @OnClick({R.id.iv_up, R.id.iv_like, R.id.btn_del, R.id.btn_share, R.id.btn_replay})
    public void onViewClicked(View view) {
        if (LetterApp.authUser == null) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        switch (view.getId()) {
            case R.id.iv_up:
                up();
                break;
            case R.id.iv_like:
                like();
                break;
            case R.id.btn_del:
                del();
                break;
            case R.id.btn_share:
                share();
                break;
            case R.id.btn_replay:
                repaly();
                break;

        }
    }

    private void repaly() {
        String jsonString = GsonUtils.toJson(model.getFromUser());
        try {
            User.UserListBean userListBean = GsonUtils.fromJson(jsonString, new TypeToken<User.UserListBean>() {
            });

            LatLng from = new LatLng(LetterApp.curLocation.getLatitude(), LetterApp.curLocation.getLongitude());
            LatLng to = new LatLng(model.getFromUser().getLatitude(), model.getFromUser().getLongitude());

            float distance = AMapUtils.calculateLineDistance(from, to);
            String stringTime = String.format(Locale.US, "%.2f", distance / 1000);
            userListBean.setDistance(Double.parseDouble(stringTime));


            Intent intent = new Intent(this, LetterWriterActivity.class);
            intent.putExtra("model", userListBean);
            startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void del() {
        AlertDialog alertDialog = new AlertDialog.Builder(this).setMessage("是否删除这份信").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                showLoading("");
                fetchDel();
            }
        }).setNegativeButton("取消", null).create();
        alertDialog.show();
    }

    private void share() {
        View view = View.inflate(this, R.layout.view_dialog_share, null);
        View viewHole = view.findViewById(R.id.layout_share_hole);
        viewHole.setTag("1");
        viewHole.setOnClickListener(shareCLick);

        View viewWx = view.findViewById(R.id.layout_share_wx);
        viewWx.setTag("2");
        viewWx.setOnClickListener(shareCLick);


        BottomSheetDialog dialog = new BottomSheetDialog(this);
        dialog.setContentView(view);
        dialog.show();
    }


    private View.OnClickListener shareCLick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            WXWebpageObject textContent = new WXWebpageObject();

            textContent.webpageUrl = "http://www.network404.cn/share/index.html?id=" + model.getId();

            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo_straight);
            WXMediaMessage media = new WXMediaMessage(textContent);
            media.title = model.getTitle();
            media.description = model.getText();
            media.thumbData = ImageUtils.bitmap2byte(bitmap,30);

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = "xxx";
            req.message = media;
            req.scene = view.getTag().toString().equals("2") ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
            IWXAPI api = WXAPIFactory.createWXAPI(LetterDetailActivity.this, Constants.WX_APP_ID);
            api.sendReq(req);

        }
    };

    private void fetchDel() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("userId", LetterApp.authUser.getId());
        hashMap.put("letterId", model.getId());
        hashMap.put("type", "sender".equals(role) ? "1" : "2");
        HttpUtils.post(Constants.Url.Letter.LETTER_DEL, hashMap, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                try {
                    BaseModel baseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel>() {
                    });
                    if (baseModel.isSuccess()) {
                        showToast("删除成功");
                    } else {
                        showToast(baseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                hideLoading();
                showErrorParse();
            }
        });
    }

    private void up() {
        HttpUtils.post(Constants.Url.Letter.LETTER_UP, getPostData(), new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    BaseModel<Integer> stringBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<Integer>>() {
                    });
                    if (stringBaseModel.isSuccess()) {
                        if (stringBaseModel.data == 1) {
                            model.setGood(model.getGood() + 1);
                            mIvUp.setSelected(true);
                        } else {
                            model.setGood(model.getGood() - 1);
                            mIvUp.setSelected(false);
                        }
                        mTvUpCnt.setText(model.getGood() + "");
                    } else {
                        showToast(stringBaseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                showErrorNet();
            }
        });
    }

    private void like() {
        HttpUtils.post(Constants.Url.Letter.LETTER_LIKE, getPostData(), new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    BaseModel<Integer> stringBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<Integer>>() {
                    });
                    if (stringBaseModel.isSuccess()) {
                        if (stringBaseModel.data == 1) {
                            showToast("收藏成功");
                            mIvLike.setSelected(true);
                        } else {
                            showToast("取消收藏成功");
                            mIvLike.setSelected(false);
                        }
                    } else {
                        showToast(stringBaseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                showErrorNet();
            }
        });
    }

    private HashMap<String, String> getPostData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("letterId", model.getId());
        map.put("userId", LetterApp.authUser.getId());
        return map;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
